<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--      筛选-->
      <!--      分栏24占满 -->
      <el-col :span="24" :xs="24">
        <el-row style="display: flex;align-items: center;justify-content: flex-start" :gutter="10" class="mb8">
          <el-form :inline="true" >
            <el-form-item label="用户列表">
              <reference ref="problemReference" :component="() => import('@/views/system/user/index')"
                         title="用户参照"
                         @input="getRef"
                         :multiple="true"
                         :show-reference-box="false"
                         :operation="{value : 'id' , label : 'userName'}"
                         v-model="registerUserList" />
            </el-form-item>
            <el-form-item>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-form-item>
          </el-form>

        </el-row>
        <el-table row-key="id"
                  ref="mainTable"
                  v-loading="loading"
                  :data="data"
                  @current-change="handleCurrentChange"
                  @selection-change="handleSelectionChange" >
          <el-table-column :reserve-selection="true"
                           type="selection"
                           width="50"
                           align="center" />
          <el-table-column v-for="(item,index) in columns"
                           v-if="item.visible"
                           :key="index"
                           :label="item.label"
                           :prop="item.prop"
                           :width="item.width"
                           align="center">
            <template slot-scope="scope">
              <span  v-if="item.prop =='createTime'"  >{{ parseTime(scope.row[item.prop]) }}</span>
              <el-switch
                v-else-if="item.prop == 'status'"
                v-model="scope.row[item.prop]"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
              <span v-else-if="item.prop == 'userName'">
                {{scope.row['userVO'].userName}}
              </span>
              <el-avatar v-else-if="item.prop == 'avatar'" size="medium" :src="scope.row['userVO'].avatar"></el-avatar>
              <span v-else-if="item.prop == 'nickName'">
                {{scope.row['userVO'].nickName}}
              </span>
              <span v-else-if="item.prop == 'sex'">
                {{scope.row['userVO'].sex == 0 ? '男' : '女'}}
              </span>
              <span v-else >{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

      </el-col>

    </el-row>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="题目排序" prop="seq">
              <el-input v-model="form.seq" placeholder="请输入序号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="气球颜色" prop="color">
              <el-color-picker
                v-model="form.color"
                show-alpha
                :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in enums.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saving" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as api from '@/api/contest'
import Reference from '@/components/Reference'
export default {
  name: "ContestProblemList",
  components: { Reference },
  data() {
    return {
      registerUserList : [],
      saving:false,
      contestId:null,
      options:[],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      data: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      multiple:true,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      //批改表单
      correctionForm:{},
      //选中列表
      selectData:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        authorId:null,
        problemId:null,
        title:undefined,
        status: undefined,
        auth:undefined,
      },
      // 列信息
      columns: [
        { label: `id`, visible: false, prop:"id"},
        { label: `头像`, visible: true, prop:"avatar" },
        { label: `昵称`, visible: true, prop:"nickName"},
        { label: `账号`, visible: true, prop:"userName"},
        { label: `性别`, visible: true, prop:"sex"},
        { label: `状态`, visible: true, prop:"status"},
        { label: `报名时间`, visible: true, prop:"createTime" },
        { label: `修改时间`, visible: false, prop:"updateTime" },
      ],
      // 表单校验
      rules: {
        seq: [
          { required: true, message: "序号不能为空", trigger: "blur" },
        ]
      },
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ]
    };
  },

  async created() {
    this.contestId = this.$route.query.id;
    if(this.contestId == null){
      this.$modal.msgError("没有选中比赛");
      return;
    }
    await this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      this.loading = true;
      const res = await api.getRegisterUserList(this.addDateRange(this.queryParams, this.dateRange),this.contestId);
      this.data = res.data.rows;
      this.total = res.data.total;
      this.registerUserList = this.data.map(item => item.userVO)
      this.loading = false;
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === 1 ? "停用" : "启用";
      this.$modal.confirm('确认要'+ text + '？').then(function() {
        return api.updateContestProblem({ id: row.id, status : row.status});
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    /**  表单重置 */
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      if(this.type !=1 ){
        console.log(selection)
        console.log("多选选中了")
        this.selectData = selection
        this.multiple = !selection.length;
      }

    },
    /** 单选框选中数据 */
    handleCurrentChange(selection){
      if(this.type == 1){
        console.log(selection)
        console.log("单选选中了")
        this.selectData = [selection]
        this.multiple = !this.selectData.length;
      }

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let Ids = this.selectData.map(item => item.id);
      if(row && row.id)
        Ids = [row.id]
      this.$modal.confirm('是否确认删除').then(function() {
        return api.del(Ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 修改按钮操作 */
    handleUpdate(row){
      this.reset();
      this.form = row;
      this.title = "修改题目";
      this.open = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saving = true;
          if (this.form.id != undefined) {
            api.updateContestProblem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() =>{
              this.saving = false;
            })
          } else {
            api.updateContestProblem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() =>{
              this.saving = false;
            })
          }
        }
      });
    },
    /** 取消按钮*/
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 参照改变*/
    getRef(list){
      console.log(list)
      const data = []
      let increase = false;
      let reduce = false;
      list.forEach(item => {
        const index = this.data.map(e => e.uid).indexOf(item.userId)
        if(index == -1){
          increase = true;
        }
        const dataItem = {
          uid:item.userId,
          cid:this.contestId,
        }
        data.push(dataItem)
      })
      const removeList = []
      this.data.forEach(item => {
        const index = list.map(e => e.userId).indexOf(item.uid)
        if(index == -1){
          reduce = true;
          removeList.push(item.userVO.userName)
        }

      })
      if(reduce){
        this.$modal.confirm('是否确认移除用户名为：【"' + removeList.join(",") + '"】的用户？').then(() => {
          api.addRegisterUser(data).then(res => {
            this.$modal.msgSuccess("操作成功");
            this.getList();
          })
        }).catch(err => {

        })
      }else{
        if(increase || reduce)
          api.addRegisterUser(data).then(res => {
            this.$modal.msgSuccess("操作成功");
            this.getList();
          })
      }

    }

  }
};
</script>
<style>

</style>
